package org.csu.mypetstore.web.servlets;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.csu.mypetstore.domain.Product;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class AutoCompleteServlet extends HttpServlet {
    private String keyword;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        keyword =  req.getParameter("keyword");
        CatalogService service = new CatalogService();
        List<Product> products = service.searchProductListWithLimit(keyword);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json; charset=utf-8");
        String jsonString = JSON.toJSONString(products);
        JSONArray array = JSON.parseArray(jsonString);
        JSONObject object = new JSONObject();
        object.put("tipItems", array);
//        jsonString = JSON.toJSONString(object);
        PrintWriter out = resp.getWriter();
        out.print(object);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
